'''
Created on 2020年3月6日

@author: yinfs
'''
import os
import hashlib
import exifread
import random
import uuid
from dao import pcsdao

class FileUtil(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        
    def get_photo_list(self,filePath,extensionTypeList):
        '''
                    获取指定目录下包含特定文件扩展名的文件。
        :return  文件信息列表
        '''
        fileList = []
        for top, dirs, nondirs in os.walk(filePath):
            for item in nondirs:
                (filename, extension) = os.path.splitext(item) 
                if extension in extensionTypeList:
                    fileList.append(os.path.join(top, item))
        return fileList
    
    def get_photo_info_list(self,filePath,extensionTypeList):
        '''
                    获取指定目录下包含特定文件扩展名的文件。
        :return  文件信息列表
        '''
        i = 0
        fileList = []
        for top, dirs, nondirs in os.walk(filePath):
            for item in nondirs:
                (filename, extension) = os.path.splitext(item) 
                if extension in extensionTypeList:
                    filePathName = os.path.join(top, item)
                    fileMd5 = self.get_file_md5(filePathName)
                    exifInfo = self.get_photo_exif(filePathName)
                    newFileName = self.get_new_filename(extension, exifInfo[0])
                    fileinfo = (filePathName,fileMd5,newFileName)+exifInfo                   
#                     print(fileinfo)
                    fileList.append(fileinfo)
                    i = i+1
                    print('需要处理的文件数：',i)
        return fileList
     
    def get_photo_info_list_partition(self,job_id,dirs_id,filePath,extensionTypeList):
        '''
                    获取指定目录下包含特定文件扩展名的文件。
        :return  文件信息列表
        '''
        pdao = pcsdao.PcsDao() 
        i = 0
        j = 0
        z = 0
        fileList = []
        for top, dirs, nondirs in os.walk(filePath):
            for item in nondirs:
                (filename, extension) = os.path.splitext(item) 
                if extension in extensionTypeList:
                    filePathName = os.path.join(top, item)
#                     print('文件名称=',filePathName)
                    fileSize = os.path.getsize(filePathName)
#                     fileSizeKB = round(fileSize/float(1024))
                    fileMd5 = self.get_file_md5(filePathName)
                    photo_exifInfo = self.get_photo_exif(filePathName)
                    newFileName = self.get_new_filename(extension, photo_exifInfo[0])
                    fileinfo = (job_id,dirs_id,filePathName,fileSize,extension,fileMd5,newFileName)+photo_exifInfo  

                    fileList.append(fileinfo)
                    i = i + 1
                    j = j + 1
                    if j == 1000:
                        z = z + 1 
                        print('向数据库提交！ ',z)
                        pdao.insert_photo_class(fileList)
                        fileList = []
                        j =0 
                    print('文件总数{0}  队列数{1}  队中数据{2} 图片名称{3} '.format(i,z,j,filePathName))
        
        print('最后一次提交 文件总数{0}  队列数{1}  队中数据{2} 图片名称{3}'.format(i,z,j,filePathName))
        pdao.insert_photo_class(fileList)
        
#         return fileList
    
    def get_directory_photo_info(self,filePath,extensionTypeList):
        '''
                    获取指定目录下包含特定文件扩展名的文件。
        :return  文件信息列表
        '''
        num_dirs = 0
        num_files = 0
        num_file_extension = 0
        num_file_extension_size = 0
        
        for top, dirs, nondirs in os.walk(filePath):
            for item in nondirs:
                num_files +=1
                (filename, extension) = os.path.splitext(item) 
                if extension in extensionTypeList:
                    filePathName = os.path.join(top, item)
#                     print('文件名称=',filePathName)
                    fileSize = os.path.getsize(filePathName)
                    num_file_extension_size +=fileSize
                    num_file_extension +=1
            
            for name in dirs:
                num_dirs +=1
#         dir_info =(num_dirs,num_files,num_file_extension,num_file_extension_size)
        dir_dict = {
            'directory_num':num_dirs,
            'file_num':num_files,
            'file_extension_num':num_file_extension,
            'file_extension_size':num_file_extension_size
            }        
#         print('num_dirs=',num_dirs)
#         print('num_files = ',num_files)
#         print('num_file_extension = ',num_file_extension)
#         print('num_file_extension_size = ',num_file_extension_size)
        return dir_dict
   
    def get_file_md5(self,filePathName):
        '''
                         对指定的文件进行MD5加密，并返回加密后的字符串
        :return str
        '''
        try:
            file = open(filePathName, "rb")
            md = hashlib.md5()
            md.update(file.read())
            res1 = md.hexdigest()
            return res1
        except Exception as e:
            print('对文件进行MD5加密错误： ', e)
            resl = 'ERR'
            return res1
    
    def get_str_md5(self,info):
        '''
                         对指定的文件进行MD5加密，并返回加密后的字符串
        :return str
        '''
        try:
            md = hashlib.md5()
            md.update(info.encode(encoding='GBK'))
            res1 = md.hexdigest()
            return res1
        except Exception as e:
            print('对字符串进行MD5加密错误： ', e)
            resl = 'ERR'
            return res1
            
    
    def get_photo_exif(self,filePathName):
        '''
                    获取指定的照片文件的 EXIF 信息，并返回
        :return 
        '''
        try:
            f = open(filePathName,'rb')
            tags = exifread.process_file(f)
            if 'Image DateTime' in tags:
                imageDatetime=tags.get('Image DateTime').values
                if  imageDatetime.__len__()<10:
                    imageDatetime ='1979-11-19 06:00:00'
                else:
                    imageDatetime = self.imgtime_conversion_datetime(imageDatetime)
            else:
                imageDatetime ='1979-11-19 06:00:00'
            
            if 'Image Make' in tags:
                imageMark=tags.get('Image Make').values
            else:
                imageMark ='无'
    
            if 'Image Model' in tags:
                imageModel=tags.get('Image Model').values
            else:
                imageModel ='无'
    
            if 'EXIF ExifImageLength' in tags:
                imageLength=tags.get('EXIF ExifImageLength').values
            else:
                imageLength ='0'
    
            if 'EXIF ExifImageWidth' in tags:
                imageWidth=tags.get('EXIF ExifImageWidth').values
            else:
                imageWidth ='0'
    
#             exifInfo = (imageDatetime,imageMark,imageModel,imageLength[0],imageWidth[0]) 
                
        except Exception as e:
            print('获取文件exif 信息错误：',e)
            print('文件名为：',filePathName)
            
#         return exifInfo
#         print((imageDatetime,imageMark,imageModel,imageLength[0],imageWidth[0]))
        return (imageDatetime,imageMark,imageModel,imageLength[0],imageWidth[0])
    
    def imgtime_conversion_datetime(self,imageDatetime):
        '''
        将 yyyy:MM:dd hh:mm:ss 的时间格式 转换成   yyyy-MM-dd hh:mm:ss
        :return str
        '''
        imageDatetimeArr = imageDatetime.split(' ')
        imageDate = imageDatetimeArr[0].replace(':','-')
        return (imageDate+' '+imageDatetimeArr[1])
    
    def get_new_filename(self,extension,imageDatetime):
        '''
        通过exif Image Datetime 的时间 加上 5个随机数产生一个新的 yyyyMMddhhmmss_12345 格式的文件名
        '''
        try:
          filename = imageDatetime.replace('-','').replace(':','').replace(' ','')+'_'+''.join([str(random.randint(1,9)) for i in range(5)])+extension
        except Exception as e:
            print('生成新的文件名错误：',e)
        return filename
    
    def write_csv_for_list(self,repeatList):
        '''
        将List 中的输入写入到CSV 文件中
        '''
        try:
            f = open('pcs.csv','w')
            for repeatInfo in repeatList:
                rInfo =''
                for ri in repeatInfo:
                    s = ri+','
                    rInfo = rInfo+s
                rInfo = rInfo+'\n'
                f.writelines(rInfo)
            f.close()          
        except Exception as e:
            print('将List 中的数据写入到文件中:',e)
    
    def if_directory(self,filepath):
        '''
        判断目录是否存在，如果不存在则创建一个新的目录
        '''
        flag = True
        try:
            flag = os.path.isdir(filepath)   
        except Exception as e:
            print('判断目录是否存在，如果不存在则创建一个新的目录:',e)
        return flag
    
    def get_uuid(self):
        '''
        获取UUID
        '''
        uid = str(uuid.uuid4())
        suid = ''.join(uid.split('-'))
        return suid
